package com.demo.java.OD601_650.OD637;

import java.util.*;

/**
 * @author bug菌
 * @Source 公众号：猿圈奇妙屋
 * @des： 【发现新词的数量 /新词挖掘(A卷-100分)】问题
 * @url： https://blog.csdn.net/weixin_43970743/article/details/146964523
 */
public class OdMain {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String content = in.nextLine(); // 读取主字符串
        String word = in.nextLine();    // 读取目标单词
        System.out.println(countAnagrams(content, word));
    }

    public static int countAnagrams(String content, String word) {
        if (content.length() < word.length() || word.length() == 0)
            return 0;

        // 统计word中的每个字符出现的次数
        Map<Character, Integer> wordMap = new HashMap<>();
        for (char c : word.toCharArray()) {
            wordMap.put(c, wordMap.getOrDefault(c, 0) + 1);
        }

        Map<Character, Integer> windowMap = new HashMap<>();
        int matchKind = 0; // 窗口中与word频率完全相同的字符种类数量
        int result = 0;
        char[] contentArr = content.toCharArray();
        int wordLen = word.length();

        for (int right = 0; right < contentArr.length; right++) {
            char cur = contentArr[right];
            // 加入右边字符
            windowMap.put(cur, windowMap.getOrDefault(cur, 0) + 1);
            if (wordMap.containsKey(cur) &&
                    windowMap.get(cur).intValue() == wordMap.get(cur).intValue()) {
                matchKind++;
            }

            // 维持窗口大小
            if (right >= wordLen) {
                char leftChar = contentArr[right - wordLen];
                if (wordMap.containsKey(leftChar) &&
                        windowMap.get(leftChar).intValue() == wordMap.get(leftChar).intValue()) {
                    matchKind--;
                }
                windowMap.put(leftChar, windowMap.get(leftChar) - 1);
            }

            // 所有字符频率都匹配，说明是一个有效新词
            if (matchKind == wordMap.size()) {
                result++;
            }
        }
        return result;
    }
}